package com.srwl.mytx.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.util.Util;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.google.gson.GsonBuilder;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.LiveRecord;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.MulctItem;
import com.srwl.mytx.domain.Orders;
import com.srwl.mytx.domain.Present;
import com.srwl.mytx.domain.Reward;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.fragment.ConversationListFragment;
import com.srwl.mytx.im.LiveRoomService;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.LiveService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.SystemUtil;
import com.srwl.mytx.utils.TextUtil;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.BarrageLayout;
import com.srwl.mytx.widget.KeyboardAwareRelativeLayout;
import com.srwl.mytx.widget.LiveCountDownView;
import com.srwl.mytx.widget.LiveMemberJoinSpecialView;
import com.srwl.mytx.widget.LiveMemberJoinView;
import com.srwl.mytx.widget.LiveOfferView;
import com.srwl.mytx.widget.LivePresentView;
import com.srwl.mytx.widget.MultipleCouponView;
import com.srwl.mytx.widget.RoomMessagesView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import qiu.niorgai.StatusBarCompat;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.srwl.mytx.adapter.OrderRecordAdapter.REQUEST_CODE_OFFER;

/**
 * Created by wei on 2016/6/12.
 */
public abstract class BaseChatRoomActivity extends BaseActivity implements LivePresentView.PresentListListener {
    protected static final String TAG = "ChatRoomActivity";
    protected static final int COUNTDOWN_DELAY = 1000;
    protected static final int COUNTDOWN_START_INDEX = 3;//开始直播倒计时读秒
    public static final int COUNTDOWN_END_INDEX = 1;

    @BindView(R.id.left_gift_view1)
    LivePresentView leftGiftView;
    @BindView(R.id.left_gift_view2)
    LivePresentView leftGiftView2;
    @BindView(R.id.message_view)
    RoomMessagesView messageView;
    @BindView(R.id.bottom_bar)
    View bottomBar;
    @BindView(R.id.barrage_layout)
    BarrageLayout barrageLayout;

    @BindView(R.id.new_messages_warn)
    ImageView newMsgNotifyImage;
    @BindView(R.id.live_member_join_view)
    LiveMemberJoinView liveMemberJoinView;
    @BindView(R.id.live_member_join_view_special)
    LiveMemberJoinSpecialView liveMemberJoinSpecialView;
    @BindView(R.id.offer_view)
    LiveOfferView offerView;
    @BindView(R.id.tv_offer_amount)
    TextView tv_offerAmount;
    @BindView(R.id.iv_offer)
    ImageView iv_offer;
    @BindView(R.id.rl_video_container)
    RelativeLayout rl_videoContainer;
    @BindView(R.id.iv_boo)
    ImageView iv_boo;
    @BindView(R.id.root_layout)
    KeyboardAwareRelativeLayout rootLayout;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.count_down_view)
    LiveCountDownView countDownView;

    @BindView(R.id.cover_image)
    ImageView coverView;
    @BindView(R.id.iv_red_packet)
    MultipleCouponView couponView;
    @BindView(R.id.red_packet_num)
    TextView tv_red_Packet_Num;
    @BindView(R.id.iv_advertisement)
    ImageView iv_advertisement;
    @BindView(R.id.video_player)
    JzvdStd videoPlayer;
    protected User anchor;
    protected boolean isMessageListInited;
    List<Reward> rewardList = Collections.synchronizedList(new LinkedList<>());
    List<Orders> ordersList = new ArrayList<>();
    protected LiveRoomService liveRoomService;


    public List<Topic> goodsList = new ArrayList<>();
    LiveRoom liveRoom;


    //标记角色：是否是主播
    Boolean isAnchor;
    //标记是否是直播状态
    boolean isLiveStarted;
    DisplayMetrics dm;
    protected Topic bindGoods;
    protected GsonBuilder builder;
    protected User myUserInfo;
    protected int booCount;//记录收到的点踩数量
    private List<ImageView> booViewList = new ArrayList<>();
    private boolean isOfferShowing;
    protected LiveRecord liveRecord;
    protected Advertisement advertisement;
    List<Present> presents;
    List<MulctItem> mulctItemList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            finish();
        }
        liveRoom = getIntent().getParcelableExtra(Constant.EXTRA_INFO_LIVE_ROOM);
        //直播
        // initEventHandle();

        myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        onActivityCreate(savedInstanceState);
        leftGiftView.setListener(this);
        leftGiftView2.setListener(this);
        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        builder = new GsonBuilder();

        //判断是否是刘海屏（对华为 小米 oppo vivo 4个手机品牌做判断）
        View statusBar = findViewById(R.id.status_bar);
        NotchScreenManager.getInstance().getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
            @Override
            public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
                Log.i(TAG, "Is this screen notch? " + notchScreenInfo.hasNotch);
                if (notchScreenInfo.hasNotch) {
                    statusBar.setVisibility(View.GONE);
                } else {
                    //如果不是刘海屏，就设置为全屏
                    SoftKeyboardFixerForFullscreen.assistActivity(BaseChatRoomActivity.this);
                    StatusBarCompat.translucentStatusBar(BaseChatRoomActivity.this, true);
                    int statusBarHeight = Utils.getStatusBarHeight(BaseChatRoomActivity.this);
                    if (statusBarHeight != 0) {
                        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
                        layoutParams.height = statusBarHeight;
                        statusBar.setLayoutParams(layoutParams);
                    }
                }
            }
        });
        rootLayout.addOnKeyboardHiddenListener(new KeyboardAwareRelativeLayout.OnKeyboardHiddenListener() {
            @Override
            public void onKeyboardHidden() {
                //当软键盘折叠后，隐藏输入框
                messageView.hideInputView();
                bottomBar.setVisibility(View.VISIBLE);
            }
        });
    }


    @OnClick(R.id.iv_advertisement)
    public void toAdvertisementActivity_1() {

        startActivityForResult(new Intent(getBaseContext(), PutAdvertisementActivity.class)
                .putExtra("liveRoom", liveRoom), REQUEST_CODE_OFFER);
    }

    public void refreshGoodsList(String anchorId) {
        String bql = "getImageInfo include anchor,* from Goods where anchor=?";
//        new BmobQuery<Goods>().doSQLQuery(bql, new SQLQueryListener<Goods>() {
//            @Override
//            public void done(BmobQueryResult<Goods> bmobQueryResult, BmobException e) {
//                if (e == null) {
//                    if (bmobQueryResult != null) {
//                        goodsList.addAll(bmobQueryResult.getResults());
//                        goodsDateChange();
//                    }
//                }
//            }
//        }, anchorId);
    }


    protected abstract void onActivityCreate(@Nullable Bundle savedInstanceState);


    protected synchronized void showLeftGiftView(Reward reward) {

        if (!leftGiftView.isUseGift(reward) && !leftGiftView2.isUseGift(reward)) {
            rewardList.add(reward);
        }

    }

    /**
     * 从服务端加载礼物信息
     */
    void initData() {
        if (!Helper.getInstance().isNetworkConnected()) {
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(LiveService.class).getAllPresent().enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                CommonResult body = response.body();

                // Log.d("返回的礼物数据:"+ (body.getData()))
                if (!response.isSuccessful()) {
                    Log.e(TAG, "onResponse: " + response.message());
                    return;
                }

                JSONArray jsonArray = (JSONArray) body.getData();
                if (jsonArray == null) {
                    return;
                }
                presents = jsonArray.toJavaList(Present.class);
                //setVp(mListener,presents);
                leftGiftView.setPresents(presents);
                leftGiftView2.setPresents(presents);
                Log.d(TAG, "礼物列表" + jsonArray.toJSONString());


            }


            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                Log.e(TAG, "礼物请求失败onFailure: " + t.getMessage());
            }
        });


    }

    /**
     * 从本地加载礼物信息
     */
    void initLocalPrentData() {

        presents = new ArrayList<>();
        presents.add(new Present("1fen", R.drawable.p_1fen, 0.01));
        presents.add(new Present("2fen", R.drawable.p_2fen, 0.02));
        presents.add(new Present("5fen", R.drawable.p_5fen, 0.05));
        presents.add(new Present("1jiao", R.drawable.p_1jiao, 0.1));
        presents.add(new Present("2jiao", R.drawable.p_2jiao, 0.2));
        presents.add(new Present("5jiao", R.drawable.p_5jiao, 0.5));
        presents.add(new Present("1yuan", R.drawable.p_1yuan, 1.0));
        presents.add(new Present("2yuan", R.drawable.p_2yuan, 2.0));
        presents.add(new Present("5yuan", R.drawable.p_5yuan, 5.0));
        presents.add(new Present("10yuan", R.drawable.p_10yuan, 10.0));
        presents.add(new Present("50yuan", R.drawable.p_50yuan, 50.0));
        presents.add(new Present("100yuan", R.drawable.p_100yuan, 100.0));
    }

    void initMulctItems() {
        mulctItemList = new ArrayList<>();
        mulctItemList.add(new MulctItem("1fen", R.drawable.tx_boo, 0.01));
    }

    private synchronized Reward getReward() {
        if (rewardList.size() == 0) {
            return null;
        }
        return rewardList.remove(0);
    }

    protected void showBooView() {
        ImageView booView = null;
        int randomY = 0;
        int randomX;
        for (int i = 0; i < booViewList.size(); i++) {
            ImageView imageView = booViewList.get(i);
            if (imageView.getTranslationY() == 0) {
                Random random = new Random();
                int max = Utils.dpToPx(100, this);
                randomY = random.nextInt(max);
                randomX = random.nextInt(max);
                if (random.nextBoolean()) {
                    randomY = -randomY;
                }
                if (random.nextBoolean()) {
                    randomX = -randomX;
                }
                imageView.setTranslationY(randomY);
                imageView.setTranslationX(randomX);
                Log.d(TAG, "showBooView: booViewList.size()" + booViewList.size() + "    i:" + i);
                booView = imageView;

                break;
            } else {
                if (i == booViewList.size() - 1) {
                    if (booViewList.size() < 10) {//屏幕上最多显示10个点踩图标
                        booView = getImageView();
                    } else {
                        return;//如果5个全都显示在屏幕上，那就return
                    }

                }
            }
        }
        if (booView == null) {
            booView = getImageView();
        }

        final ImageView finalBooView = booView;
        finalBooView.setVisibility(View.VISIBLE);
        ViewAnimator.animate(booView)
                .alpha(0, 1).scale(3, 1).duration(400)
                .thenAnimate(booView)
                .translationY(0 + randomY, -70 + randomY, 30 + randomY, -70 + randomY, 30 + randomY, -70 + randomY, 30 + randomY).rotation(0, -30, 0, -30, 0, -30, 0).duration(1500)
                .thenAnimate(booView)
                .alpha(1, 0).translationY(1.5f * iv_boo.getHeight() + randomY).duration(600)
                .onStop(new AnimationListener.Stop() {
                    @Override
                    public void onStop() {
                        booCount--;
                        finalBooView.setTranslationY(0);
                        if (booCount >= 1) {
                            showBooView();
                        }
                    }
                })
                .start();
    }

    @NonNull
    private ImageView getImageView() {

        ImageView booView = new ImageView(this);
        booView.setBackgroundResource(R.drawable.tx_boo);
        RelativeLayout.LayoutParams params = getLayoutParams();
        booView.setVisibility(View.GONE);
        rootLayout.addView(booView, params);
        booViewList.add(booView);
        return booView;
    }

    @NonNull
    private RelativeLayout.LayoutParams getLayoutParams() {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//        Random random = new Random();
//        int i = random.nextInt(Utils.dpToPx(100, this));//生成随机数
//        params.bottomMargin = screenHeight / 2 - i;
//        int leftMargin = (int) ((screenWidth - iv_boo.getWidth()) * Math.random());
//        params.leftMargin = leftMargin < iv_boo.getWidth() ? iv_boo.getWidth() : leftMargin;
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        return params;
    }


    protected void showOffer(final Orders orders) {
        if (isOfferShowing) {
            ordersList.add(orders);
            return;
        }
        isOfferShowing = true;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                offerView.setupView(orders);
                if (!offerView.isShown()) {
                    offerView.setVisibility(View.VISIBLE);
                }
                if (!tv_offerAmount.isShown()) {
                    tv_offerAmount.setVisibility(View.VISIBLE);
                }
                tv_offerAmount.setText(Utils.numberFormat(orders.getAmount()));
                ViewAnimator.animate(tv_offerAmount)
                        .alpha(0, 1)
                        .scale(4, 1)
                        .duration(800)
                        .onStop(() -> {
                            isOfferShowing = false;
                            if (ordersList.size() != 0) {
                                showOffer(ordersList.remove(0));
                            }
                        })
                        .start()
                ;
            }
        });
    }

    protected void initMessageView() {

        messageView.init(liveRoom);
        messageView.setMessageViewListener(new RoomMessagesView.MessageViewListener() {
            @Override
            public void onMessageSend(Message message) {
                liveRoomService.sendMessage(message);
                Utils.hideKeyboard(messageView.getInputView());
            }


        });
        messageView.setVisibility(View.VISIBLE);
        messageView.setShowInputView(false);
        // bottomBar.setVisibility(View.VISIBLE);
        isMessageListInited = true;
        //  updateUnreadMsgView();


    }


    /* private void showUserDetailsDialog(User user) {
         final UserDetailsDialog dialog =
                 UserDetailsDialog.newInstance(user);
         dialog.setUserDetailsDialogListener(
                 new UserDetailsDialog.UserDetailsDialogListener() {
                     @Override
                     public void onMessageClick(User user) {
                         dialog.dismiss();
                         Bundle bd = new Bundle();
                         // bd.putCharSequence("userId", user.getuId());
                         bd.putParcelable(Constant.EXTRA_TARGET_USER_INFO, user);
                         ChatFragment chatFragment = new ChatFragment();
                         chatFragment.setArguments(bd);
                         chatFragment.show(getSupportFragmentManager(), "ChatFragment");
                     }

                     @Override
                     public void onMentionClick(String username) {
                         dialog.dismiss();
                         messageView.getInputView().setText("@" + username + " ");
                         showInputView();
                     }
                 });
         dialog.show(getSupportFragmentManager(), "UserDetailsDialog");
     }
 */
    private void showInputView() {
        bottomBar.setVisibility(View.INVISIBLE);
        messageView.setShowInputView(true);
        messageView.setVisibility(View.VISIBLE);
        messageView.getInputView().requestFocus();
        messageView.getInputView().requestFocusFromTouch();
        Utils.showKeyboard(messageView.getInputView());

//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Utils.showKeyboard(messageView.getInputView());
//
//            }
//        }, 200);
    }

    @OnClick(R.id.root_layout)
    void onRootLayoutClick() {
        // periscopeLayout.addHeart();
    }

    @OnClick(R.id.rl_comment)
    void onCommentImageClick() {
        showInputView();
    }


    @OnClick(R.id.chat_image)
    void onChatImageClick() {
        ConversationListFragment fragment = new ConversationListFragment();
//    getSupportFragmentManager().beginTransaction()
//        .replace(R.id.message_container, fragment)
//        .commit();
        fragment.show(getSupportFragmentManager(), "ConversationListFragment");
    }

//    @OnClick(R.id.screenshot_image)
//    void onScreenshotImageClick() {
//    Bitmap bitmap = screenshot();
//    if (bitmap != null) {
//      ScreenshotDialog dialog = new ScreenshotDialog(this, bitmap);
//      dialog.show();
//    }
//
//    }

    private Bitmap screenshot() {
        // 获取屏幕
        View dView = getWindow().getDecorView();
        dView.setDrawingCacheEnabled(true);
        dView.buildDrawingCache();
        Bitmap bmp = dView.getDrawingCache();
        return bmp;
    }

    @Override
    public void onDisappear() {
        Reward reward = getReward();
        if (reward == null) {
            return;
        }

        showLeftGiftView(reward);


        // TODO: 2019/3/24 遍历礼物集合 如果是同一用户同类型礼物则合并 并增加计数


        // List<Reward> rewardList1 = new ArrayList<>();
        for (int i = 0; i < rewardList.size(); i++) {
            Reward reward3 = rewardList.get(i);
            if (reward != null
                    && reward3.getuId().equals(reward.getuId())
                    && Double.doubleToLongBits(reward3.getAmount()) == Double.doubleToLongBits(reward.getAmount())) {

                reward3 = rewardList.remove(i);
                Log.d(TAG, "Reward3的id " + reward3.getuId());
                i--;
                //rewardList1.add(reward);


                showLeftGiftView(reward3);
            }

        }

    }


    void resetLiveRoom() {
        anchor = null;
        bindGoods = null;
        goodsList = null;
    }


    protected void setLocalVideo() {


//        SurfaceView surfaceViewLocal = RtcEngine.CreateRendererView(getBaseContext());
//        surfaceViewLocal.setZOrderOnTop(true);
//        surfaceViewLocal.setZOrderMediaOverlay(true);
//        surfaceViewLocal.setTag("local");
//        rl_videoContainer.addView(surfaceViewLocal, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//
//        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceViewLocal, VideoCanvas.RENDER_MODE_HIDDEN, 0));
//
//        //设置预览
//        mRtcEngine.startPreview();
    }

    protected void setRemoteVideo(int uid) {

//        SurfaceView surfaceViewRemote = RtcEngine.CreateRendererView(getBaseContext());
//        surfaceViewRemote.setZOrderOnTop(true);
//        surfaceViewRemote.setZOrderMediaOverlay(true);
//        surfaceViewRemote.setTag("remote");
//
//        rl_videoContainer.addView(surfaceViewRemote, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
//        mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceViewRemote, VideoCanvas.RENDER_MODE_HIDDEN, uid));
//        // mRtcEngine.setRemoteDefaultVideoStreamType(VIDEO_STREAM_HIGH);
    }

    /**
     * 清空视频容器
     */
    protected void removeVideoView() {
        rl_videoContainer.removeAllViews();
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    protected void showCover() {
        if (TextUtils.equals("MI 8 SE", SystemUtil.getSystemModel())) {//小米8se ，不能满屏，必须手动设置高度，获取的屏幕高度是2029，也是不准确的，
            ViewGroup.LayoutParams layoutParams = coverView.getLayoutParams();
            layoutParams.height = 2164;
            coverView.setLayoutParams(layoutParams);
            ViewGroup.LayoutParams layoutParams1 = videoPlayer.getLayoutParams();
            layoutParams1.height = 2164;
            videoPlayer.setLayoutParams(layoutParams1);
        }
        if (!TextUtils.isEmpty(liveRoom.getVideo())) {
            String url = liveRoom.getVideo();
            String remoteUrl;
            if (url != null && url.startsWith("http")) {
                remoteUrl = url;
            } else {
                remoteUrl = AliOssService.TOPIC_VIDEO_PRE_URL + url;
            }
            setVideoPlayer(remoteUrl);
            videoPlayer.setVisibility(View.VISIBLE);
            videoPlayer.closeControlProgress();
            coverView.setVisibility(View.GONE);
            videoPlayer.startVideo();

            String remoteCoverUrl = getCoverUrl();
            if (Util.isOnMainThread()) {
                String scale50Url = Utils.getLiveRoomListAdapterUrl(liveRoom);
                if (GlideLoadUtils.isActivityAlive(this)) {
                    Glide.with(this).load(remoteCoverUrl).thumbnail(Glide.with(this).load(scale50Url)).diskCacheStrategy(DiskCacheStrategy.ALL).into(videoPlayer.thumbImageView);
                }
            }
        } else {
            videoPlayer.setVisibility(View.GONE);
            coverView.setVisibility(View.VISIBLE);
            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            String remoteUrl = getCoverUrl();
            if (Util.isOnMainThread()) {
                //先用封面小图来作为缩略图，因为小图已经被加载到本地了，这样避免打开直播间，在缓冲封面大图的时间内，看到的是空白，
                String scale50Url = Utils.getLiveRoomListAdapterUrl(liveRoom);
                if (GlideLoadUtils.isActivityAlive(this)) {
                    Glide.with(this).load(remoteUrl).thumbnail(Glide.with(this).load(scale50Url)).diskCacheStrategy(DiskCacheStrategy.ALL).into(coverView);
                }
            }
        }
    }

    private String getCoverUrl() {
        String url = liveRoom.getCover();
        String remoteUrl;
        if (url != null && url.startsWith("http")) {
            remoteUrl = url;
        } else {
            remoteUrl = AliOssService.TOPIC_IMAGE_PRE_URL + url;
        }
        return remoteUrl;
    }

    protected void showAdvertisement() {
        if (advertisement == null) {
            return;
        }
            String videoUrl = advertisement.getVideo();
        if (!TextUtils.isEmpty(videoUrl)) {
            String remoteUrl;
            if ( videoUrl.startsWith("http")) {
                remoteUrl = videoUrl;
            } else {
                remoteUrl = AliOssService.TOPIC_VIDEO_PRE_URL + videoUrl;
            }
            setVideoPlayer(remoteUrl);
            String videoCover = advertisement.getPicture();
            if (TextUtils.isEmpty(videoCover)) {
                videoCover = remoteUrl;
            }else {
                if ( !videoCover.startsWith("http")) {
                    videoCover = AliOssService.TOPIC_IMAGE_PRE_URL + videoCover;
                }
//                else {
//                    videoCover=videoCover;
//                }
            }
            //GlideLoadUtils.glideLoad(this, videoCover, videoPlayer.thumbImageView);
            String scale50Url = Utils.getLiveRoomListAdapterUrl(liveRoom);
            if (GlideLoadUtils.isActivityAlive(this)) {
                Glide.with(this).load(videoCover).thumbnail(Glide.with(this).load(scale50Url)).diskCacheStrategy(DiskCacheStrategy.ALL).into( videoPlayer.thumbImageView);
            }
            if (!videoPlayer.isShown()) {
                videoPlayer.setVisibility(View.VISIBLE);
                coverView.setVisibility(View.GONE);
            }
            // videoPlayer.startButton.performClick();
            videoPlayer.startVideo();

        } else if (!TextUtils.isEmpty(advertisement.getPicture())) {
            if (!couponView.isShown()) {
                coverView.setVisibility(View.VISIBLE);
                videoPlayer.setVisibility(View.GONE);
            }
            String url = advertisement.getPicture();
            String remoteUrl;
            if (url != null && url.startsWith("http")) {
                remoteUrl = url;
            } else {
                remoteUrl = AliOssService.TOPIC_IMAGE_PRE_URL + url;
            }
            // Glide.with(this).load(remoteUrl).diskCacheStrategy(DiskCacheStrategy.ALL).into(coverView);
            // GlideLoadUtils.glideLoad(this, remoteUrl, coverView);
            String scale50Url = Utils.getLiveRoomListAdapterUrl(liveRoom);
            if (GlideLoadUtils.isActivityAlive(this)) {
                Glide.with(this).load(remoteUrl).thumbnail(Glide.with(this).load(scale50Url)).diskCacheStrategy(DiskCacheStrategy.ALL).into(coverView);
            }
        }
    }

    protected void setVideoPlayer(String url) {
        ViewGroup.LayoutParams params = videoPlayer.getLayoutParams();
        params.height = getResources().getDisplayMetrics().heightPixels;//设置videoPlayer 高度为屏幕高度
        LinkedHashMap map = new LinkedHashMap();
        String proxyUrl = MyApplication.getProxy(this).getProxyUrl(url);//视频缓存代理
        map.put("高清", proxyUrl);
        JZDataSource jzDataSource = new JZDataSource(map, "");
        jzDataSource.looping = false;
        JzvdStd.setVideoImageDisplayType(Jzvd.VIDEO_IMAGE_DISPLAY_TYPE_FILL_CROP);
        // jzDataSource.currentUrlIndex = 2;
        videoPlayer.setUp(jzDataSource, JzvdStd.SCREEN_FULLSCREEN);
        videoPlayer.hideAllViewAdaptFullScreen();
        // videoPlayer.bottomContainer.setVisibility(View.VISIBLE);
        videoPlayer.thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }


}
